package com.ins1st.util;

import com.alibaba.fastjson.JSON;
import com.ins1st.api.SysUploadApi;
import com.ins1st.base.R;
import com.ins1st.entity.SysUpload;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;
import java.util.UUID;

/**
 * @program: ins1st-cloud
 * @description:
 * @author: coderSun
 * @create: 2019-11-21 15:00
 **/
@Component
public class QiNuiUpload {

    @Value("${qiniu.access-key}")
    private String AccessKey;
    @Value("${qiniu.secret-key}")
    private String SecretKey;
    @Value("${qiniu.bucket}")
    private String bucket;
    @Value("${qiniu.url}")
    private String url;
    @Autowired
    private SysUploadApi sysUploadApi;

    private static final Logger log = LoggerFactory.getLogger(QiNuiUpload.class);

    private Auth auth;
    private Configuration cfg;
    private UploadManager uploadManager;

    private void init() {
        if (auth == null) {
            cfg = new Configuration(Region.autoRegion());
            uploadManager = new UploadManager(cfg);
            auth = Auth.create(this.AccessKey, this.SecretKey);
            log.info("七牛云OSS初始化完毕......");
        }
    }

    public R<SysUpload> upload(Object object, String key) {
        init();
        try {
            Response response = null;
            if (object instanceof byte[]) {
                response = uploadManager.put((byte[]) object,
                        StringUtils.isNotBlank(key) ? key : UUID.randomUUID().toString().replace("-", ""),
                        auth.uploadToken(bucket));
            }
            if (object instanceof File) {
                response = uploadManager.put((File) object,
                        StringUtils.isNotBlank(key) ? key : UUID.randomUUID().toString().replace("-", ""),
                        auth.uploadToken(bucket));
            }
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            log.info("OSS:{},上传方式:byte数组,文件标识名:{}","七牛云",key);
            SysUpload sysUpload = new SysUpload();
            sysUpload.setUploadType("1");
            sysUpload.setFileKey(putRet.key);
            sysUpload.setUploadTime(new Date());
            sysUploadApi.insert(sysUpload);
            sysUpload.setShowUrl(url + putRet.key);
            return sysUploadApi.insert(sysUpload);
        } catch (QiniuException e) {
            return R.fail();
        }

    }
}
